<template>
  <div id="half" class="half">
    <div>
      <div class="info">
        <div v-if="this.isChina()" class="txt-div" style="margin-top: 52px">
          <div class="txt-bg">我距离马沟</div>
          <div class="info-text">
            {{ distance }}
          </div>
        </div>
        <div class="txt-div" :style="this.isChina() ? '' : 'margin-top: 52px'">
          <div class="txt-bg">下潜深度</div>
          <div class="info-text">
            {{ deepDistance }}
          </div>
        </div>
        <div class="txt-div">
          <div class="txt-bg">识别生物</div>
          <div class="info-text">{{ finishFish }}/{{ allFish }}</div>
        </div>
        <div class="txt-div">
          <div class="txt-bg">致敬中国马沟成就</div>
          <span class="info-text"> {{ finishHonor }}/{{ allHonor }} </span>
        </div>
      </div>
    </div>
    <div class="bottom-btn-div">
      <!-- <img
        class="bottom-btn"
        @click="onClickRank"
        :src="this.defaultConfig.btnShare"
      /> -->
      <img
        class="bottom-btn"
        @click="onClickShow"
        :src="this.defaultConfig.btnShare"
      />
    </div>
    <div class="share">
      <div id="share-info" class="share-info">
        <img
          class="share-info-bg"
          src="https://sapi.yangshipin.cn/assets/x/other/deepDiving/picture/share/bg.png"
        />
        <div id="share-info-head" class="share-info-head">
          <img
            class="share-info-head-border"
            src="https://sapi.yangshipin.cn/assets/x/other/deepDiving/picture/share/border.png"
          />
          <img
            id="share-info-head-user"
            class="share-info-head-user"
            :src="headImgUrl"
          />
          <img
            id="share-info-head-spare"
            class="share-info-head-spare"
            v-if="!isLoadedHead"
            src="https://sapi.yangshipin.cn/assets/x/other/deepDiving/picture/share/default.png"
          />
        </div>
        <div class="share-name">{{ nickname }}</div>
        <div class="share-info-grade1">
          <div class="share-info-grade1-title">我距离马沟</div>
          <div class="share-info-grade1-grade">{{ distance }}</div>
        </div>
        <div class="share-info-grade2">
          <div class="share-info-grade2-title">下潜深度</div>
          <div class="share-info-grade2-grade">{{ deepDistance }}</div>
        </div>
        <div class="share-info-grade3">
          <div class="share-info-grade3-title">识别生物</div>
          <div class="share-info-grade3-grade">
            {{ finishFish }} / {{ allFish }}
          </div>
        </div>
        <div class="share-info-grade4">
          <div class="share-info-grade4-title">致敬中国马沟成就</div>
          <div class="share-info-grade4-grade">
            {{ finishHonor }} / {{ allHonor }}
          </div>
        </div>
      </div>
    </div>
    <div class="share-canvas" :style="{ display: canvasDisplay }">
      <img class="share-canvas-url" :src="canvasUrl" />
      <!-- <div class="share-canvas-remind" v-if="!isAndroid()">
        长按图片保存至相册，分享给好友
      </div>
      <div class="share-canvas-remind" v-if="isAndroid()">
        点击图片保存至相册，分享给好友
      </div> -->
      <img
        class="share-canvas-close"
        src="https://sapi.yangshipin.cn/assets/x/other/deepDiving/picture/share/close.png"
        @click="onClickClose"
      />
      <img
        class="share-canvas-download"
        src="https://sapi.yangshipin.cn/assets/x/other/deepDiving/picture/share/download.png"
        @click="onClickDownload"
      />
      <img
        class="share-canvas-share"
        src="https://sapi.yangshipin.cn/assets/x/other/deepDiving/picture/share/share.png"
        @click="onClickShare"
      />
    </div>
  </div>
</template>

<script>
import html2canvas from "html2canvas";
import ActiveApi from "../io/active";
import dataUrlToFile from "../util/dataUrlToFile";
import getCosSdk from "../util/getCosSdk";

export default {
  name: "Alert",
  data() {
    return {
      distance: "",
      deepDistance: "10909",
      finishFish: 0,
      allFish: 0,
      finishHonor: 0,
      allHonor: 0,
      nickname: "万米深潜",
      headImgUrl: "",
      isLoadedHead: false,
      canvasDisplay: "none",
      canvasUrl: "",
      isCompleted: false,
      shareUrl: "",
      tryCount: 0,
    };
  },
  methods: {
    isAndroid() {
      var u = navigator.userAgent;
      return u.indexOf("Android") > -1 || u.indexOf("Adr") > -1;
    },
    isChina() {
      if (localStorage.getItem("YspIpSourceForeign")) return false;
      return true;
    },
    /**
     * 总榜关闭回调
     */
    rankCallBack() {
      //
    },
    /**
     * 查看总榜
     */
    onClickRank() {
      this.createRank({
        callback: this.rankCallBack,
      });
    },
    async onClickShow() {
      if (navigator.userAgent.indexOf("yangshipin") >= 0) {
        if (this.isLoadedHead) {
          this.onHtml2Canvas();
        } else {
          var User = window["cctvh5-account"].default;
          let isSigned = await User.isSigned();
          if (isSigned) {
            if (this.tryCount < 2) this.tryCount++;
            // 第二次点击，假设还没加载成功头像，则用默认海报
            if (this.tryCount == 2) {
              this.onHtml2Canvas();
            } else {
              jsbridge.toast("努力生成炫耀海报中，请稍后再试");
            }
          } else {
            User.signin();
          }
        }
      } else {
        let href =
          "https://m.yangshipin.cn/static/x/iframe/deepDiving/index.html#/game";

        console.log("分享href", href);
        let tempParam =
          "deepAction=bottom&currentDeep=10000&YspDistance=" +
          parseInt(localStorage.getItem("YspDistance")) +
          "&YspFinishHonor=" +
          parseInt(localStorage.getItem("YspFinishHonor")) +
          "&YspFishNum=" +
          parseInt(localStorage.getItem("YspFishNum"));
        if (href.indexOf("?") === -1) {
          href = href + "?" + tempParam;
        } else {
          href = href + "&" + tempParam;
        }
        this.callApp(null, null, href);
      }
    },
    onHtml2Canvas() {
      if (this.isCompleted) {
        this.canvasDisplay = "inline";
        return;
      }
      let that = this;
      that.canvasDisplay = "inline";
      that.callHtml2canvas();
    },
    callHtml2canvas() {
      let that = this;
      setTimeout(() => {
        html2canvas(document.getElementById("share-info"), {
          backgroundColor: "transparent",
          useCORS: true,
          allowTaint: true,
        }).then((canvas) => {
          let url = canvas.toDataURL("image/png");
          that.canvasUrl = url;
          that.isCompleted = true;
          that.imageUpload(url);
        });
      }, 500);
    },
    async onGetUserInfo() {
      //if (!this.isYangshipin()) return;
      var User = window["cctvh5-account"].default;
      let isSigned = await User.isSigned();
      if (isSigned) {
        let that = this;
        User.info().then(function (uinfo) {
          uinfo = JSON.stringify(uinfo);
          uinfo = JSON.parse(uinfo);
          let head = document.getElementById("share-info-head-user");
          head.setAttribute("crossOrigin", "Anonymous");
          that.headImgUrl = uinfo.headImgUrl;
          that.nickname = uinfo.nickname;
          head.onload = function () {
            that.isLoadedHead = true;
          };
        });
      } else {
        User.signin();
      }
    },
    onClickClose() {
      this.canvasDisplay = "none";
    },
    onClickDownload() {
      this.imageDownload(this.shareUrl);
    },
    onClickShare() {
      var Share = window["cctvh5-share"].default;
      const params = {
        shareId: "itemtype=aid&aid=5f9fbf5015fc6f5eb63584a5",
        shareTitle: "“奋斗万米” 致敬有你",
        shareSubTitle: "来央视频，一起探秘马里亚纳海沟！",
        shareUrl:
          "https://m.yangshipin.cn/static/x/iframe/deepDiving/index.html",
        shareImgUrl:
          "https://wimg.yangshipin.cn/pics/20201102_3hfk351e1lcshenghai.png",
        changeTagTitle: false,
      };
      if (this.isYangshipin()) {
        Share.invokeCCTVShare(params);
      }
    },
    async imageUpload(data) {
      try {
        // 异步获取临时密钥
        let crs = await ActiveApi.credentials({
          fileType: 3,
          suffix: "png",
        });
        let credentials = crs.credentials;
        let cos = await this.getCos(credentials);
        let file = dataUrlToFile(data, "poster." + "png");
        let res = await this.cosUpload(cos, {
          bucketName: credentials.bucketName,
          region: credentials.region,
          key: credentials.path,
          body: file,
        });
        let url = "http://" + res.Location;
        this.shareUrl = url;
        //this.imageDownload(url);
      } catch (err) {
        console.log(err);
      }
    },
    async imageDownload(url) {
      let rs = await jsbridge.invokeDownLoadImg(url);
      if (!this.isAndroid()) jsbridge.toast("保存成功!");
    },
    async getCos(credentials) {
      let COS = await getCosSdk();
      let cos = new COS({
        getAuthorization: function (options, callback) {
          callback({
            TmpSecretId: credentials.tmpSecretId,
            TmpSecretKey: credentials.tmpSecretKey,
            XCosSecurityToken: credentials.token,
            ExpiredTime: credentials.expiredTime,
          });
        },
      });
      return cos;
    },
    cosUpload(cos, options) {
      let conf = {
        ...options,
      };
      console.log(cos);
      return new Promise((resolve, reject) => {
        cos.putObject(
          {
            Bucket: conf.bucketName,
            Region: conf.region,
            Key: conf.key,
            Body: conf.body,
          },
          function (err, data) {
            if (err) {
              reject(err);
            } else {
              resolve(data);
            }
          }
        );
      });
    },
  },
  async mounted() {
    let that = this;
    setTimeout(() => {
      let height = parseFloat(
        window.getComputedStyle(document.getElementById("half")).height
      );
      that.tweenMove("half", 0, -height, 200);
    }, 200);
    this.onGetUserInfo();
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.txt-div {
  display: flex;
  justify-content: flex-start;
  padding: 0px 10px;
  margin-left: 20px;
  margin-top: 5px;
}
.txt-bg {
  width: 180px;
  height: 37px;
  background-image: url("https://sapi.yangshipin.cn/assets/x/other/deepDiving/static/bgBottom.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  text-align: center;
  line-height: 37px;
  color: #a6c0f1;
}
.info {
  position: absolute;
  top: 90px;
  padding: 20px 10px 10px 10px;
  width: 95%;
  height: 250px;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-image: url("https://sapi.yangshipin.cn/assets/x/other/deepDiving/static/window_achievement.png");
}
.info-text {
  margin-left: 25px;
  display: inline-block;
  font-size: 1rem;
  letter-spacing: 0.125rem;
  color: #fff;
  margin-bottom: 0.3125rem;
  line-height: 37px;
  font-weight: bold;
}
.half {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  bottom: -100%;
  z-index: 9999;
  font-family: PingFangSC-Medium, PingFang SC;
}
.bottom-btn-div {
  display: flex;
  justify-content: center;
  position: fixed;
  bottom: 5px;
  margin: 0 auto;
  width: 100%;
}
.bottom-btn {
  display: inline-block;
  width: 220px;
  height: 87px;
  z-index: 999;
}
.share-info {
  width: 300px;
  height: 533.6px;
  position: relative;
  left: 50%;
  top: 1000px;
  transform: translate(-50%, 0);
}
.share-info-bg {
  width: 300px;
  position: absolute;
  left: 50%;
  transform: translate(-50%, 0);
  border-radius: 20px;
}
.share-info-head {
  width: 60px;
  height: 60px;
  position: absolute;
  left: 50%;
  top: 50px;
  transform: translate(-50%, 0);
}
.share-info-head-border,
.share-info-head-spare {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.share-info-head-border {
  width: 54px;
}
.share-info-head-spare {
  width: 38px;
}
.share-info-head-user {
  width: 38px;
  height: 38px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.share-name {
  width: 120px;
  position: absolute;
  left: 70px;
  top: 108px;
  z-index: 1;
  color: #fdebb6;
  font-size: 16px;
  font-weight: 600;
  text-align: center;
}
.share-info-grade1,
.share-info-grade2,
.share-info-grade3,
.share-info-grade4 {
  position: absolute;
  left: 60px;
  z-index: 1;
  color: #ffede1;
  font-size: 12px;
  text-shadow: 0px 2px 2px #404581;
  text-align: center;
}
.share-info-grade1-grade,
.share-info-grade2-grade,
.share-info-grade3-grade,
.share-info-grade4-grade {
  width: 60px;
  position: absolute;
  left: 125px;
  top: 0;
  text-align: left;
  color: white;
}
.share-info-grade1 {
  top: 253px;
}
.share-info-grade2 {
  top: 283px;
}
.share-info-grade3 {
  top: 314px;
}
.share-info-grade4 {
  top: 344px;
}
.share-canvas {
  width: 375px;
  height: 800px;
  position: fixed;
  left: 50%;
  top: 0;
  transform: translate(-50%, 0);
  z-index: 9999;
  background-color: rgba(0, 0, 0, 0.8);
}
.share-canvas-url {
  width: 260px;
  position: absolute;
  left: 50%;
  top: 10px;
  transform: translate(-50%, 0);
}
.share-canvas-remind {
  width: 300px;
  position: absolute;
  left: 50%;
  top: 480px;
  transform: translate(-50%, 0);
  color: white;
  text-align: center;
}
.share-canvas-close,
.share-canvas-download,
.share-canvas-share {
  width: 40px;
  position: absolute;
  top: 510px;
  transform: translate(-50%, 0);
}
.share-canvas-close {
  left: 30%;
}
.share-canvas-download {
  left: 50%;
}
.share-canvas-share {
  left: 70%;
}
</style>
